package com.cml.rpc.server;

import com.cml.rpc.publicinterface.UserService;
import com.cml.rpc.publicpojo.RpcRequest;
import com.cml.rpc.publicpojo.RpcResponse;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 服务端
 * @author cml
 * @create 2021/7/20 15:33
 */
public class RpcServer {
    public static void main(String[] args) {
        UserService userService = new UserServiceImpl();
        try {
            ServerSocket serverSocket = new ServerSocket(8877);
            System.out.println("服务端启动.....");

            while (true) {
                Socket accept = serverSocket.accept();
                // 当监听到客户端的请求，就创建一个线程处理请求
                new Thread(() -> {
                    try {
                        ObjectOutputStream oos = new ObjectOutputStream(accept.getOutputStream());
                        ObjectInputStream ois = new ObjectInputStream(accept.getInputStream());
                        // 通过反射调用对应方法
                        RpcRequest rpcRequest = (RpcRequest)ois.readObject();
                        Method method = userService.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParamTypes());
                        // 调用invoke拿到调用结果
                        Object invoke = method.invoke(userService, rpcRequest.getParams());

                        System.out.println("服务端处理结果response.data = " + invoke);
                        // 封装response,将响应发送给客户端
                        oos.writeObject(RpcResponse.success(invoke));
                        oos.flush();
                        System.out.println("-------------------------------");
                    } catch (IOException | ClassNotFoundException | NoSuchMethodException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("服务端启动失败！");
        }
    }
}
